#!/usr/bin/python -tt
import sys, Image, ImageDraw, os, re

def find_images(source):
  sourcefiles = os.listdir(source)
  imagefiles = []
  for i in range(len(sourcefiles)):
    match = re.search(r'[\w-]+\.jpg', str(sourcefiles))
    if not match:
      match = re.search(r'[\w-]+\.gif', str(sourcefiles))
    if not match:
      match = re.search(r'[\w-]+\.jpeg', str(sourcefiles))
    if not match:
      match = re.search(r'[\w-]+\.png', str(sourcefiles))
    if match:
      a = sourcefiles.index(match.group())
      sourcefiles.pop(a)
      if match.group() in imagefiles:
        a = 1
      else:
        imagefiles.append(match.group())
  print '\nFound ' + str(len(imagefiles)) + ' image files!'
  return imagefiles
 
def process_images(indir, outdir, fname):
  if not os.path.exists(outdir):
    os.makedirs(outdir)
    print 'Output folder created'
  print '\n\nProcessing...',	
  if indir[-1:] != '\\':
    indir = indir + '\\'
  if outdir[-1:] != '\\':
    outdir = outdir + '\\'
  for f in fname:
    im = Image.open(indir + f)
    x, y = im.size
    if x > y:
      background = Image.new('RGB', (x, x), '#FFFFFF')
      background.paste(
        im,
        (0, (x - y) / 2))
    elif y > x:
      background = Image.new('RGB', (y, y), '#FFFFFF')
      background.paste(
        im,
        ((y - x) / 2, 0))
    elif x == y:
      background = im
    x, y = background.size
    if x > 850:
      image = background.resize((850, 850), Image.ANTIALIAS)
    else:
      image = background
    image.save(outdir+f[:-3] + 'jpg', "JPEG") 
   
   

def main():
  dir = sys.argv
  del dir[0]
  if len(dir) == 0:
    print "\nPlease specify a source directory\ni.e. image.py c:\\images\n\nYou may also specify an ouput directory\ni.e. image.py c:\\images c:\\output"
    sys.exit(0)
  elif len(dir) == 1:
    print '\nSource Directory: ' + str(dir)
    print 'Default Output Directory: c:\\resize'
    imagefiles = find_images(dir[0])
    if len(imagefiles) > 0:
      process_images(dir[0], 'c:\\resize',imagefiles)
    print 'Done'
  elif dir[0] == dir[1]:
    print "\nPlease specify a different output directory!\n- This is to avoid destroying your originals..."
    sys.exit(0)
  elif len(dir) == 2:
    print '\nSource Directory: ' + dir[0]
    print 'Output Directory: ' + dir[1]
    imagefiles = find_images(dir[0])
    if len(imagefiles) > 0:
      process_images(dir[0], dir[1],imagefiles)
    print 'Done'
  else:
    print "\nInput unknown!\n\nPlease specify a source directory\ni.e. image.py c:\\images\n\nYou may also specify an ouput directory\ni.e. image.py c:\\images c:\\output"
    sys.exit(0)
if __name__ == '__main__':
  main()
